package com.yunyike.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yunyike.constants.CommonConstant;
import com.yunyike.mapper.UserMapper;
import com.yunyike.model.User;
import com.yunyike.redis.JedisManager;
import com.yunyike.service.IUserService;
import com.yunyike.utils.UserUtils;

@Service("userServiceImpl")
public class UserServiceImpl implements IUserService{

	private Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private UserMapper userMapper;
	
	public List<User> findAllUsers() {
		// TODO Auto-generated method stub
		return null;
	}

	public User findUserById(String userId) {
		// TODO Auto-generated method stub
		return userMapper.selectByPrimaryKey(userId);
	}

	/**
	 * 隐形注册
	 */
	public int addUserInvisible(User user) {
		log.info("----->> add user invisible ....");
		
		// 判断用户是否存在
		User dbUser = userMapper.selectByOpenId(user.getUserOpenId());
		
		// 已存在
		if(dbUser != null){
			log.info("user already exist.return success.");
			return CommonConstant.NUMBER_1;
		}
		
		// 不存在隐形注册
		log.info("user is not exist,add user...");
		user.setCtime(new Date());
		user.setUserId(UUID.randomUUID().toString());
		user.setUserOriginId(CommonConstant.NUMBER_0);
		
		int result = 0;
		try {
			result = userMapper.insertSelective(user);
		} catch (Exception e) {
			log.info("add user invisible has errors,message:"+e.getMessage(),e);
		}
		return result;
	}

	/**
	 * 根据手机号登录
	 */
	public void login(String mobile, String password,HttpServletRequest request,
			HttpServletResponse response) {

	}

	/**
	 * 根据openId登录
	 */
	public void login(String openId,HttpServletRequest request,
			HttpServletResponse response) {
		
		User user = null;
		try {
			// 根据openId获取用户信息
			user = userMapper.selectByOpenId(openId);
		} catch (Exception e) {
			log.error("login by openId ,select by openId has error:message:"+e.getMessage(),e);
		}
		
		// 用户不存在
		if(user == null){
			log.error("login by openId,but no this openId,please check.openId:"+openId);
			return;
		}
		
		// 登录
		doLogin(user, request, response);
	}
	
	/**
	 * 登录
	 * @param user
	 */
	private void doLogin(User user,HttpServletRequest request,
			HttpServletResponse response){

		String sessionId = UserUtils.getSessionId(request, response);
		
		try {
			JedisManager.setObject(sessionId, CommonConstant.USER_KEY_ET, user);
		} catch (Exception e) {
			log.error("set user to redis has errors:message:"+e.getMessage(),e);
		}
	}

	public int update(User user) {
		return userMapper.updateByPrimaryKeySelective(user);
	}

}
